package sz.szsmk.citizencard.mvp.presenter;

import android.util.Log;

import com.google.gson.Gson;
import com.youzan.spiderman.utils.MD5Utils;

import javax.inject.Inject;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import sz.szsmk.citizencard.DaggerApplication;
import sz.szsmk.citizencard.log.L;
import sz.szsmk.citizencard.model.network.GsdxNetApi;
import sz.szsmk.citizencard.model.network.RxSubscribers;
import sz.szsmk.citizencard.model.network.bean.request.IBaseRequest;
import sz.szsmk.citizencard.model.network.bean.request.RealNameCertificationLRequest;
import sz.szsmk.citizencard.model.network.bean.response.AliUserInfoBean;
import sz.szsmk.citizencard.model.network.bean.response.BaseBean;
import sz.szsmk.citizencard.model.network.bean.response.CheckIsChargeRes;
import sz.szsmk.citizencard.model.network.bean.response.FirstSearchUserLevelRes;
import sz.szsmk.citizencard.model.network.bean.response.IbaseBean;
import sz.szsmk.citizencard.model.network.bean.response.OauthTokenRes;
import sz.szsmk.citizencard.model.network.dzbean.req.BaseRequest;
import sz.szsmk.citizencard.model.network.dzbean.req.CommonRequest;
import sz.szsmk.citizencard.model.network.dzbean.req.GetOpenIdReq;
import sz.szsmk.citizencard.model.network.dzbean.req.PreAuthThiedReq;
import sz.szsmk.citizencard.model.network.dzbean.req.PreAuthThirdRes;
import sz.szsmk.citizencard.model.network.dzbean.req.QueryDzsmkAgreementReq;
import sz.szsmk.citizencard.model.network.dzbean.res.CheckIsRealName2Res;
import sz.szsmk.citizencard.model.network.dzbean.res.CheckIsRealNameRes;
import sz.szsmk.citizencard.model.network.dzbean.res.GetOpenIdRes;
import sz.szsmk.citizencard.model.network.dzbean.res.PreAuthResult;
import sz.szsmk.citizencard.model.network.dzbean.res.QueryDzsmkAgreeMentRes;
import sz.szsmk.citizencard.mvp.contract.IMainContact;
import sz.szsmk.citizencard.mvp.contract.IRealNameContact;
import sz.szsmk.citizencard.retrofitrxjava.DZSmkAppInit;
import sz.szsmk.citizencard.retrofitrxjava.ErrorAction;
import sz.szsmk.citizencard.retrofitrxjava.NetworkDateSources;
import sz.szsmk.citizencard.retrofitrxjava.SubscribeResult;
import sz.szsmk.citizencard.smkretrofit.NetworkDateSource;
import sz.szsmk.citizencard.ui.adapter.bean.AppHomeCardBean;
import sz.szsmk.citizencard.util.ACache;
import sz.szsmk.citizencard.util.AndroidUtils;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.ObjectSignatureUtil;
import sz.szsmk.citizencard.util.StringUtils;
import sz.szsmk.citizencard.widget.GlobalVariables;

/**
 * Copyright (c)2018
 * author: zdh
 * created on: 2018/12/18 15:32
 * description:
 */
public class RealNamePresenter extends IBasePresenter
        implements IRealNameContact.IRealNamePresenter<IRealNameContact.IRealNameView> {

    private NetworkDateSources mNetworkDateSource;
    GsdxNetApi gsdxNetApi;
    private int userId;
    private final NetworkDateSource instance;
    private String openId;
    private String channelId;
    private String mobile;
    private String token1;

    @Inject
    public RealNamePresenter(GsdxNetApi gsdxNetApi) {
        this.gsdxNetApi = gsdxNetApi;
        this.mNetworkDateSource = NetworkDateSources.getInstance();
        instance = NetworkDateSource.getInstance();
    }

    @Override
    public void firstSearchUserLevel() {
        IBaseRequest baseRequest = new IBaseRequest();
        String access_token = ACache.get(DaggerApplication.getIns()).getAsString("access_token");
        baseRequest.setAccess_token(access_token);
        String androidId = AndroidUtils.getAndroidId(DaggerApplication.getIns());
        baseRequest.setDevice_id(AndroidUtils.getAndroidId(DaggerApplication.getIns()));
        String refresh_token = ACache.get(DaggerApplication.getIns()).getAsString("refresh_token");
        String key = "access_token=" + access_token + "&device_id=" + androidId + "&key=" + refresh_token;
        String stringMd5 = MD5Utils.getStringMd5(key).toUpperCase();
        baseRequest.setSign(stringMd5);
        String json = new Gson().toJson(baseRequest);
        mNetworkDateSource.firstSearchUserLevel(baseRequest, new SubscribeResult<FirstSearchUserLevelRes>() {
            @Override
            protected void onOk(FirstSearchUserLevelRes response) {
                String json = new Gson().toJson(response);
                L.e(Constant.TAG, "认证等级---" + json);
                if (response.getData() == null || response.getData().getRecognitionLevel() == null) {
                    ((IRealNameContact.IRealNameView) mView).firstSearchUserLevelFail(response);
                    return;
                }
                AppHomeCardBean appHomeCardBean = new AppHomeCardBean();
                if (!StringUtils.isBlank(response.getData().getRecognitionLevel().getL3())) {
                    appHomeCardBean.setLevel("L3");
                    appHomeCardBean.setLevelDesc(response.getData().getRecognitionLevel().getL3());
                } else if (!StringUtils.isBlank(response.getData().getRecognitionLevel().getL2())) {
                    appHomeCardBean.setLevel("L2");
                    appHomeCardBean.setLevelDesc(response.getData().getRecognitionLevel().getL2());
                } else if (!StringUtils.isBlank(response.getData().getRecognitionLevel().getL1())) {
                    appHomeCardBean.setLevel("L1");
                    appHomeCardBean.setLevelDesc(response.getData().getRecognitionLevel().getL1());
                }
                if (response.getData().getRecognitionLevel() != null) {
                    String l2 = response.getData().getRecognitionLevel().getL2();
                    if (l2 != null) {
                        String[] split = l2.split("\\+");
                        String idCard = split[1];
                        appHomeCardBean.setIdCard(idCard);
                        Constant.USER_IDCARD = idCard;
                    }
                }
                appHomeCardBean.setCustName(response.getData().getCustName());
                Constant.USER_NAME = response.getData().getCustName();
//                appHomeCardBean.setIdCard(response.getData().getEcityCardNo());
                appHomeCardBean.setEcityCardNo(response.getData().getEcityCardNo());
                ((IRealNameContact.IRealNameView) mView).firstSearchUserLevelSucc(appHomeCardBean);
            }

            @Override
            protected void onFailure(FirstSearchUserLevelRes response) {
                super.onFailure(response);
                ((IRealNameContact.IRealNameView) mView).firstSearchUserLevelFail(response);
            }

            @Override
            protected void onNext(FirstSearchUserLevelRes response) {
                super.onNext(response);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });
    }

    @Override
    public void realNameCertification(final String name, final String idCard) {
        RealNameCertificationLRequest request = new RealNameCertificationLRequest();
        String access_token = ACache.get(DaggerApplication.getIns()).getAsString("access_token");
        request.setAccess_token(access_token);
        request.setActual_name(name);
        request.setId_no(idCard);
        request.setIs_permission(0);
        String json = new Gson().toJson(request);
        L.e(Constant.TAG, "L2认证入参报文----" + json);
        mNetworkDateSource.realNameCertificationL(request, new SubscribeResult<IbaseBean>() {
            @Override
            protected void onOk(IbaseBean response) {
                String json = new Gson().toJson(response);
                L.e(Constant.TAG, "认证等级---" + json);
                Constant.USER_IDCARD = idCard;
                Constant.USER_NAME = name;
                ((IRealNameContact.IRealNameView) mView).realNameCertificationSucc();
            }

            @Override
            protected void onFailure(IbaseBean response) {
                super.onFailure(response);
                ((IRealNameContact.IRealNameView) mView).realNameCertificationFail(response);
            }

            @Override
            protected void onNext(IbaseBean response) {
                super.onNext(response);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });
    }

    @Override
    public void getOpenId() {
        GetOpenIdReq getOpenIdReq = new GetOpenIdReq();
        String access_token = ACache.get(DaggerApplication.getIns()).getAsString("access_token");
        getOpenIdReq.setUser_type(0);
        getOpenIdReq.setAccess_token(access_token);
        String s = new Gson().toJson(getOpenIdReq);
        L.e(Constant.TAG, "getOpenid----" + s);
        gsdxNetApi.getOpenId(getOpenIdReq)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscribers<GetOpenIdRes>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    protected void _onNext(GetOpenIdRes response) {
//                        getOpenIdRes = response;
                        String json = new Gson().toJson(response);
                        L.e(Constant.TAG, "getOpenId---->" + json);
                        openId = response.getOpenId();
                        userId = response.getUserId();
                        mobile = response.getMobile();
                        ACache.get(DaggerApplication.getIns()).remove("openId");
                        ACache.get(DaggerApplication.getIns()).put("openId", openId + "");
                        ACache.get(DaggerApplication.getIns()).put("userId", response.getUserId() + "");
                        PreAuthResult preAuthResult = new PreAuthResult();
                        preAuthResult.setOpenId(response.getOpenId());
                        GlobalVariables.getInstance(DZSmkAppInit.getInstance().getContext()).setPreAuthResult(DaggerApplication.getIns(), preAuthResult);
                        String openId1 = GlobalVariables.getInstance(DZSmkAppInit.getInstance().getContext()).getPreAuthResult().getOpenId();
                        if (response.getCode().equals("000000")) {
                            (((IRealNameContact.IRealNameView) mView)).getOpenIdSucc(response);
                        } else {
                            (((IRealNameContact.IRealNameView) mView)).getOpenIdFail(response);
                        }
                    }

                    @Override
                    protected void _onError(String message) {
                        Log.e("zdh", "请求失败" + message);
                    }
                });
    }

    @Override
    public void queryDzsmkAgreement(final String openId) {
        QueryDzsmkAgreementReq queryDzsmkAgreementReq = new QueryDzsmkAgreementReq();
        queryDzsmkAgreementReq.setOpenId(openId);
        queryDzsmkAgreementReq.setUserType(0);
        String json = new Gson().toJson(queryDzsmkAgreementReq);
        L.e(Constant.TAG, "queryDzsmkAgreement---->" + json);
        mNetworkDateSource.queryDzsmkAgreement(queryDzsmkAgreementReq, new SubscribeResult<QueryDzsmkAgreeMentRes>() {
            @Override
            protected void onOk(QueryDzsmkAgreeMentRes response) {
                String toJson = new Gson().toJson(response);
                channelId = response.getChannelId();
                ACache.get(DaggerApplication.getIns()).put("channelId", channelId);
                L.e(Constant.TAG, "queryDzsmkAgreement---->" + toJson);
                ((IRealNameContact.IRealNameView) mView).queryDzsmkAgreementSucc(response, openId);
            }

            @Override
            protected void onFailure(QueryDzsmkAgreeMentRes response) {
                super.onFailure(response);
                ((IRealNameContact.IRealNameView) mView).queryDzsmkAgreementFail(response);
                if (response.getCode().equals("000005")) {
                    ACache.get(DaggerApplication.getIns()).put("channelId", "000003");
//                    preAuthThird(openId, "2");
                }
                ((IMainContact.IMainView) mView).queryDzsmkAgreementFail(response);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });
    }

    @Override
    public void preAuth(String channelId, String openId) {

        PreAuthThiedReq preAuthThiedReq = new PreAuthThiedReq();
        preAuthThiedReq.setMobileNumber(mobile);
        preAuthThiedReq.setOpenId(openId);
        preAuthThiedReq.setUserId(userId+"");
        preAuthThiedReq.setPhotoUrl("");
//        String channelId = ACache.get(DaggerApplication.getIns()).getAsString("channelId");
        preAuthThiedReq.setChannelId(channelId);

        ObjectSignatureUtil.signaturePreAuthRequest(preAuthThiedReq);
        String toJson = new Gson().toJson(preAuthThiedReq);
        L.e(Constant.TAG, "------->" + toJson);
        instance.preAuthThird(preAuthThiedReq, new Action1<PreAuthThirdRes>() {
            @Override
            public void call(PreAuthThirdRes preAuthRes) {
                String code = preAuthRes.getCode();
                if (code.equals("0000")) {
                    PreAuthThirdRes.DataBean data = preAuthRes.getData();
                    token1 = data.getToken();
                    String json = new Gson().toJson(data);
                    ACache.get(DaggerApplication.getIns()).put("token", preAuthRes.getData().getToken());
                    PreAuthResult preAuthResult = new Gson().fromJson(json, PreAuthResult.class);
                    GlobalVariables.getInstance(DZSmkAppInit.getInstance().getContext()).setPreAuthResult(DaggerApplication.getIns(), preAuthResult);
                    PreAuthResult authResult = GlobalVariables.getInstance(DZSmkAppInit.getInstance().getContext()).getPreAuthResult();
                    String token = authResult.getToken();
                    ((IRealNameContact.IRealNameView) mView).preAuthSucc(preAuthRes);
                    L.e(Constant.MTAG, "存储的token：" + token);

                } else {
                    ((IRealNameContact.IRealNameView) mView).preAuthFail();
                }


            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {
                L.e(Constant.TAG, "--------------------" + throwable.getMessage());
            }
        });


    }

    @Override
    public void checkIsOpenElecCard(String openId) {
        CommonRequest request = new CommonRequest();
        request.setOpenId(openId);
        ObjectSignatureUtil.signaturePreAuthRequest(request);
        String toJson = new Gson().toJson(request);
        L.e(Constant.TAG, "checkIsRealName------>" + toJson);

        instance.checkIsRealName2(request,new SubscribeResult<CheckIsRealName2Res>(){

            @Override
            protected void onOk(CheckIsRealName2Res preAuthRes) {
                if (preAuthRes.getCode().equals("0000")) {
                    ((IRealNameContact.IRealNameView) mView).checkIsOpenElecCardSucc2(preAuthRes);
                } else {
//                    ((IRealNameContact.IRealNameView) mView).checkIsOpenElecCardFail(preAuthRes);
                }
            }

            @Override
            protected void onFailure(CheckIsRealName2Res response) {
                super.onFailure(response);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });

    }

    @Override
    public void checkIsCharge() {
        CommonRequest commonRequest = new CommonRequest();
        commonRequest.setOpenId(openId);

        ObjectSignatureUtil.signatureZhsz(commonRequest, "");
        instance.checkIsCharge(commonRequest, new Action1<CheckIsChargeRes>() {
            @Override
            public void call(CheckIsChargeRes ibaseBean) {
                String toJson = new Gson().toJson(ibaseBean);
                L.e(Constant.TAG, "checkIsCharge--->" + toJson);
                ((IRealNameContact.IRealNameView) mView).checkIsChargeSucc(ibaseBean);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {
//                ((IMainContact.IMainView) mView).checkIsChargeFail();
            }
        });
    }

    //获取阿里的串
    public void getAliString(){
        mNetworkDateSource.oauthToken2(new BaseRequest(), new Action1<OauthTokenRes>() {
            @Override
            public void call(OauthTokenRes bean) {
                ((IRealNameContact.IRealNameView) mView).getAliStringSuccess (bean.getSign());

            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {
            }
        });
    }

    //查询授权
    public void getAlicode(BaseRequest baseRequest){

        mNetworkDateSource.getAlipayUserInfo(baseRequest, new Action1<BaseBean>() {
            @Override
            public void call(BaseBean bean) {
                if(bean.getCode().equals("0000")){
                    ((IRealNameContact.IRealNameView) mView).getAlipayUserInfo(bean);
                }else{
                    ((IRealNameContact.IRealNameView) mView).getAlipayUserInfoFail(bean);
                }
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {
            }
        });
    }


    public void finishL3() {

    }
}
